package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.enume.OrderStatusEnum;
import com.atguigu.common.exception.NoWareStockException;
import com.atguigu.common.to.SkuStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SecKillSkuInfoTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.order.Cons.OrderConst;
import com.atguigu.gulimall.order.config.MyOrderInterceptor;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.WareSkuLockTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public void a() {
        //获取到代理对象
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void b() {

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c() {

    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo getConfirmInfo() throws Exception {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取登录的用户信息
        MemberEntityVo memberEntityVo = MyOrderInterceptor.threadLocal.get();
        Long memberId = memberEntityVo.getId();

        //在执行异步之前将threadlocal中的数据先获取一份，再单独放到每个异步任务中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();


        //改写为异步
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //放入请求的上下文信息
            RequestContextHolder.setRequestAttributes(attributes);
            //1.收货地址列表信息
            List<MemberReceiveVo> memberAddresses = memberFeignService.getMemberAddresses(memberId);
            //设置信息
            orderConfirmVo.setMemberReceiveVoList(memberAddresses);
        }, threadPoolExecutor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //放入请求的上下文信息
            RequestContextHolder.setRequestAttributes(attributes);
            //2.商品列表信息(购物车中获取)
            List<ProductItem> cartItems = null;
            try {
                cartItems = cartFeignService.getCartItems();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            orderConfirmVo.setProductItemList(cartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            //继续异步查询商品的库存状态(调用远程服务)
            List<ProductItem> itemList = orderConfirmVo.getProductItemList();
            //购物车中的商品编号列表
            List<Long> skuIdList = itemList.stream().map((item) -> {
                return item.getSkuId();
            }).collect(Collectors.toList());

            R stockResp = wareFeignService.hashStock(skuIdList);
            List<SkuStockTo> stockToList = stockResp.getData(new TypeReference<List<SkuStockTo>>() {
            });
            //转换为map    key=skuId value=sku->stock
            Map<Long, Boolean> stockMap = stockToList.stream().collect(Collectors.toMap(SkuStockTo::getSkuId, SkuStockTo::getHasStock));
            orderConfirmVo.setStockMap(stockMap);
        }, threadPoolExecutor);

        //阻塞等待
        CompletableFuture.allOf(addressFuture, cartFuture).get();


        //3.设置优惠信息
        Integer integration = memberEntityVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4.生成Token
        String orderToken = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(orderToken);

        //放入redis
        Long id = memberEntityVo.getId();
        stringRedisTemplate.opsForValue().set(OrderConst.ORDER_SUBMIT_PREFIX + id, orderToken);
        log.info("组装好的信息:" + orderConfirmVo);
        return orderConfirmVo;

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) throws Exception {
        //在线程中共享数据
        orderSubmitVoThreadLocal.set(orderSubmitVo);


        //获取登录用户
        MemberEntityVo memberEntityVo = MyOrderInterceptor.threadLocal.get();
        Long id = memberEntityVo.getId();
        OrderResponseVo orderResponseVo = new OrderResponseVo();
        //验证token
        //客户端提交过来的token
        String orderToken = orderSubmitVo.getOrderToken();
        //redis中获取
        /**
         * 以下的代码会出现安全的问题。假如用户点击提交订单的频率很快。那么很有可能两次请求都到达了比较token这里。并且两次请求都能够比较成功
         * 那么就会出现问题。所以必须保证校验token和删除token是一个原子性的。这里采用luna脚本
         *
         */
//        String redisToken = stringRedisTemplate.opsForValue().get(OrderConst.ORDER_SUBMIT_PREFIX + id);
//        if (orderToken!=null&&orderToken.equals(redisToken)){
//            //校验通过
//        }else {
//            //校验失败
//        }
        //ToDO:校验Token，幂等性处理
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long code = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(OrderConst.ORDER_SUBMIT_PREFIX + id),
                orderToken);
        if (code == 1L) {
            //校验通过
            //生成订单号
            String orderSn = IdWorker.getTimeId();
            //ToDO:创建订单、订单项等
            OrderCreateTo orderCreateTo = getOrder(orderSn);
            //ToDO: 验价
            //页面提交来的
            BigDecimal totalAmount = orderCreateTo.getOrder().getTotalAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();

            if (Math.abs(payPrice.subtract(totalAmount.add(orderCreateTo.getFare())).doubleValue()) < 0.01) {
                //校验通过
                //保存订单
                saveOrder(orderCreateTo);
                //向mq中发送消息
                rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderCreateTo.getOrder());


                //ToDo:远程锁库存
                R r = lockStock(orderSn, orderCreateTo);
                if (r.getCode() == 0) {
                    //模拟业务发生异常，导致订单回滚，库存不回滚
//                    int res = 10 / 0;

                    //锁定成功
                    orderResponseVo.setOrderEntity(orderCreateTo.getOrder());
                    orderResponseVo.setCode(0);

                    //ToDO:调用用户服务积分扣减(当前操作出现异常，并不会对扣库存进行回滚，因为是一个远程调用)

                    return orderResponseVo;
                } else {
                    //锁定失败,主动抛出异常，让事务进行回滚
                    orderResponseVo.setCode(3);
                    String msg = (String) r.get("msg");
                    //抛出异常。Transactional会感知到异常。进而进行回滚
                    throw new NoWareStockException(msg);
                }

            } else {
                //验价失败
                orderResponseVo.setCode(2);
                return orderResponseVo;
            }


        } else {
            //校验Token失败
            orderResponseVo.setCode(1);
            return orderResponseVo;
        }


    }

    private R lockStock(String orderSn, OrderCreateTo orderCreateTo) {
        WareSkuLockTo lockTo = new WareSkuLockTo();
        lockTo.setOrderSn(orderSn);
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        List<OrderItemVo> orderItemVos = orderCreateTo.getOrderItems().stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());
            return orderItemVo;
        }).collect(Collectors.toList());
        lockTo.setLocks(orderItemVos);
        return wareFeignService.lockStock(lockTo);

    }

    private void saveOrder(OrderCreateTo orderCreateTo) {
        //获取组装好的订单
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        //获取组装好的订单项
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //保存大订单
        this.save(order);
        //批量保存订单项
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 构建所有的订单项
     *
     * @param orderSn
     * @return
     * @throws Exception
     */
    private List<OrderItemEntity> getOrderItems(String orderSn) throws Exception {
        List<ProductItem> cartItems = cartFeignService.getCartItems();
        //订单项集合
        List<OrderItemEntity> orderItemEntityList = cartItems.stream().map(cartItem -> {
            //构建订单项
            OrderItemEntity orderItemEntity = buildOrderItem(cartItem, orderSn);


            return orderItemEntity;
        }).collect(Collectors.toList());
        return orderItemEntityList;
    }

    /**
     * 构建订单项
     *
     * @param cartItem
     * @param orderSn
     * @return
     */
    private OrderItemEntity buildOrderItem(ProductItem cartItem, String orderSn) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1. 订单编号
        orderItemEntity.setOrderSn(orderSn);
        //2. spu信息
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo data = spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setSpuBrand(data.getBrandId().toString());


        //3. sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuName(cartItem.getTitle());
        String skuAttrvalues = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrvalues);
        //设置数量
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4. 商品优惠信息
        //5. 送积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().intValue());
        //成长积分
        orderItemEntity.setIntegrationAmount(cartItem.getPrice());
        //6. 订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //订单项的实际金额： 总额-优惠金额
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);


        //设置订单项的价格
        return orderItemEntity;
    }

    /**
     * 构建订单
     *
     * @param orderSn
     * @return
     * @throws Exception
     */
    private OrderCreateTo getOrder(String orderSn) throws Exception {
        OrderCreateTo createTo = new OrderCreateTo();
        //TODO:1.构建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        createTo.setOrder(orderEntity);
        //ToDO:2.构建订单项
        //创建订单项
        List<OrderItemEntity> orderItems = getOrderItems(orderSn);
        createTo.setOrderItems(orderItems);

        //ToDO:3.计算价格
        buildPrice(orderEntity, orderItems);

        createTo.setPayPrice(orderEntity.getPayAmount());
        createTo.setFare(orderEntity.getFreightAmount());

        return createTo;
    }

    /**
     * 计算价格
     *
     * @param orderEntity
     * @param orderItems
     */
    private void buildPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItems) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);


    }

    private OrderEntity buildOrder(String orderSn) {
        MemberEntityVo memberEntityVo = MyOrderInterceptor.threadLocal.get();
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);

        //设置当前用户的登录信息
        orderEntity.setMemberId(memberEntityVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberEntityVo.getUsername());

        //获取运费&地址信息


        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //运费
        orderEntity.setFreightAmount(fareVo.getFare());
        //获取到收货地址信息
        MemberReceiveVo address = fareVo.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }


    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }


    /**
     * 关闭订单的逻辑
     *
     * @param order
     */
    @Override
    public void closeOrder(OrderEntity order) {
        String orderSn = order.getOrderSn();
        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        //如果订单的状态为待支付状态，那么就对订单进行关闭
        if (orderEntity != null && orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(orderEntity);
        }

        //主动向库存的队列中发送一条消息，进行库存的释放

        /**
         * return new Binding("stock.release.stock.queue",
         *                 Binding.DestinationType.QUEUE,
         *                 "order-event-exchange",
         *                 "order.release.other.#",
         *                 null);
         */
        OrderTo orderTo = new OrderTo();
        orderTo.setOrderSn(orderSn);
        rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);


    }

    /**
     * 根据订单号查询支付所需要的参数
     *
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {

        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        //订单号
        payVo.setOut_trade_no(orderSn);

        String subject = "";
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        subject = itemEntities.get(0).getSkuName() == null ? itemEntities.get(0).getSkuName() : "谷粒商城";
        //标题
        payVo.setSubject(subject);
        //支付的总金额
        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        return payVo;
    }

    @Override
    public PageUtils getOrderList(Map<String, Object> param) {
        //从登录拦截器的threadlocal中获取用户的信息
        MemberEntityVo memberEntityVo = MyOrderInterceptor.threadLocal.get();
        Long memberId = memberEntityVo.getId();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(param),
                new QueryWrapper<OrderEntity>().eq("member_id", memberId)
        );

        List<OrderEntity> records = page.getRecords();
        //按照修改的时间进行排序
        List<OrderEntity> orderRecord = records.stream().sorted(Comparator.comparing(OrderEntity::getModifyTime).reversed()).map(item -> {
            //查询每个订单的订单项
            String orderSn = item.getOrderSn();
            List<OrderItemEntity> orderItemEntityList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
            item.setOrderItemEntityList(orderItemEntityList);
            return item;
        }).collect(Collectors.toList());
        page.setRecords(orderRecord);
        return new PageUtils(page);

    }

    @Override
    public void updateOrserPayStatus(PayAsyncVo payAsyncVo) {
        OrderEntity orderEntity = new OrderEntity();
        String out_trade_no = payAsyncVo.getOut_trade_no();
        String trade_status = payAsyncVo.getTrade_status();
        //交易成功或者交易完成
        if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
            baseMapper.update(orderEntity, new UpdateWrapper<OrderEntity>()
                    .set("status", OrderStatusEnum.PAYED.getCode())
                    .eq("order_sn", out_trade_no));
        }
    }

    @Override
    public void createSeckillOrder(SecKillSkuInfoTo orderTo) {

        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getQuickOrderSn());
        orderEntity.setMemberId(Long.parseLong(orderTo.getUserId()));
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getCount()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getQuickOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getCount());

        //查询商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }
}
